const express = require('express');
const mysql = require('promise-mysql');

const router = express.Router();

let id = 0;

const data = [
    // { name: 'zhangsan', id: 0 },
];

// restful
// /user: get
// /user: post
// /user: delete
// /user: put

router.get('/', async function(req, res) {

    const db = await mysql.createPool({
        user: 'root',
        password: '123456',
        database: 'hello',
        port: 3306,
    }).catch((err) => {
        console.log(err);
    });

    const result = await db.query('SHOW DATABASES');

    console.log(result);

    res.send({
        status: 200,
        data,
    });
});

router.post('/', function(req, res) {
    const newItem = {
        id: id++,
        name: req.body.name,
    };
    data.push(newItem);
    res.send({
        status: 200,
        msg: '添加成功',
    });
});

router.delete('/:id', function(req, res) {
    const id = Number(req.params.id);
    const idx = data.findIndex((d) => id === d.id);
    if (idx === -1) {
        res.send({
            status: 400,
            msg: `未找到id为${id}的数据项`,
        });
        return;
    }
    data.splice(idx, 1);
    res.send({
        status: 200,
        msg: '删除成功',
    });
});

router.put('/', function (req, res) {
    const { id, name } = req.body;
    const current = data.find((d) => id === d.id);
    if (!current) {
        res.send({
            status: 400,
            msg: `未找到id为${id}的数据项`,
        });
        return;
    }
    current.name = name;
    res.send({
        status: 200,
        msg: '修改成功',
    });
});

module.exports = router;
